package com.jghz.transfer.service.impl;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.importexcel.model.CellWrapper;
import com.bstek.bdf2.importexcel.model.ExcelDataWrapper;
import com.bstek.bdf2.importexcel.model.RowWrapper;
import com.bstek.bdf2.importexcel.processor.IExcelProcessor;
import com.google.common.base.Optional;
import com.jghz.framework.exception.AppException;
import com.jghz.framework.utils.AppUtils;
import com.jghz.transfer.constant.RegexConstant;
import com.jghz.transfer.dao.WayBillDao;
import com.jghz.transfer.entity.Tbplateform;

import lombok.extern.log4j.Log4j2;

@Log4j2
@Service(WayBillExcelImport.BEAN_ID)
public class WayBillExcelImport implements IExcelProcessor {

	public static final String BEAN_ID = "sh.ImportExcelTransPlateForm";

	@Resource
	private WayBillDao wayBillDao;

	@Override
	public String getName() {
		return "交通部监测平台导入模板";
	}

	@Override
	@Transactional(rollbackFor = {}, readOnly = false)
	public int execute(ExcelDataWrapper excelDataWrapper) throws Exception {
		if (!excelDataWrapper.isValidate())
			throw new RuntimeException("当前数据没有通过验证,不能解析入库！");

		int count = 0;

		// 定义set 判断重复 电子路单号
		Set<String> sets = new HashSet<>();

		// 获得row数据集合
		Collection<RowWrapper> rowWrappers = excelDataWrapper.getRowWrappers();
		for (RowWrapper rowWrapper : rowWrappers) {

			if (rowWrapper.getRow() == 1) {
				continue;
			}

			Tbplateform plateform = new Tbplateform();
			plateform.setId(AppUtils.generateUniqueKey());
			plateform.setCompId(AppUtils.getLoginUserCompId());
			plateform.setCreateEmp(AppUtils.getLoginUserName());
			plateform.setCreateDate(AppUtils.getCurrentDate());
			plateform.setStatus("N");
			// 获得cell数据集合
			Collection<CellWrapper> cellWrappers = rowWrapper.getCellWrappers();
			for (CellWrapper cellWrapper : cellWrappers) {
				this.doProcessCell(cellWrapper, plateform);
			}
			// 签收时间要晚于发车时间
			if (StringUtils.isNotEmpty(plateform.getDespatchActualDateTime())
					&& StringUtils.isNotEmpty(plateform.getGoodsReceiptDateTime())) {
				if (plateform.getDespatchActualDateTime().compareTo(plateform.getGoodsReceiptDateTime()) >= 0) {

					String message = "运单" + plateform.getShippingNoteNumber() + "签收时间"
							+ plateform.getDespatchActualDateTime() + "要晚于发车时间" + plateform.getGoodsReceiptDateTime();
					log.error(message);
					throw new AppException(message);
				}
			}

			if (sets.contains(plateform.getOriginalDocumentNumber())) {
				String message = "存在重复电子路单号：" + plateform.getOriginalDocumentNumber();
				log.error(message);
				throw new AppException(message);
			} else {
				sets.add(plateform.getOriginalDocumentNumber());
			}
			wayBillDao.save(plateform);
			count++;
		}
		return count;
	}

	private void doProcessCell(CellWrapper cellWrapper, Tbplateform plateform) {
		Optional<Object> op = null;
		Object val = cellWrapper.getValue();
		switch (cellWrapper.getColumn()) {
		case 1:
			// 无车承运人物流交换代码
			plateform.setSenderCode(ObjectUtils.toString(val));
			break;
		case 2:
			// 原始单号 上游企业委托人运输单号
			plateform.setOriginalDocumentNumber(ObjectUtils.toString(val));
			break;
		case 3:
			// 托运单号 本电子路单号
			plateform.setShippingNoteNumber(ObjectUtils.toString(val));
			break;
		case 4:
			// 承运人 无车承运试点企业名称
			plateform.setCarrier(ObjectUtils.toString(val));
			break;
		case 5:
			// 无车承运人的统一社会信用代码
			plateform.setUnifiedSocialCreditIdentifier(ObjectUtils.toString(val));
			break;
		case 6:
			// 无车承运人的道路运输经营许可证编号
			plateform.setPermitNumber(ObjectUtils.toString(val));
			break;
		case 7:
			// 无车承运人系统正式生成运单的日期 YYYYMMDDhhmmss
			plateform.setConsignmentDateTime(ObjectUtils.toString(val));
			break;
		case 8:
			// 业务类型代码
			op = Optional.of(val);
			if (!op.isPresent()) {
				plateform.setBusinessTypeCode("1002996");
			} else {
				plateform.setBusinessTypeCode(ObjectUtils.toString(val));
			}
			break;
		case 9:
			// 货物装车后的发车时间 YYYYMMDDhhmmss
			plateform.setDespatchActualDateTime(ObjectUtils.toString(val));
			break;
		case 10:
			// 货物运到后签收时间 如签收时间无法确定,填货物运到收货地的时间 YYYYMMDDhhmmss
			plateform.setGoodsReceiptDateTime(ObjectUtils.toString(val));
			break;
		case 11:
			// 发货人 单位或个人
			plateform.setConsignor(ObjectUtils.toString(val));
			break;
		case 12:
			// 个人证件号
			plateform.setPersonalIdentityDocument(ObjectUtils.toString(val));
			break;
		case 13:
			// 装货地点 精确到区,县
			plateform.setPlaceOfLoading(ObjectUtils.toString(val));
			break;
		case 14:
			// 装货地点的国家行政区划代码
			plateform.setCountrySubdivisionCode(ObjectUtils.toString(val));
			break;
		case 15:
			// 收货人
			plateform.setConsignee(ObjectUtils.toString(val));
			break;
		case 16:
			// 收货地点
			plateform.setGoodsReceiptPlace(ObjectUtils.toString(val));
			break;
		case 17:
			// 收货地点的国家行政区划代码
			plateform.setCountrySubdivisionCode2(ObjectUtils.toString(val));
			break;
		case 18:
			// 货币总金额
			String value = ObjectUtils.toString(val);
			BigDecimal money;
			if (value.matches(RegexConstant.numberRegex) || value.matches(RegexConstant.numberRegex)) {
				money = AppUtils.getBigDecimal(value);
			} else {
				money = BigDecimal.ZERO;
			}
			if (money.equals(BigDecimal.ZERO)) {
				plateform.setTotalMonetaryAmount(BigDecimal.TEN);
			} else {
				plateform.setTotalMonetaryAmount(money);
			}
			break;
		case 19:
			// 备注
			plateform.setRemark(ObjectUtils.toString(val));
			break;
		case 20:
			// 牌照类型代码
			plateform.setLicensePlateTypeCode(ObjectUtils.toString(val));
			break;
		case 21:
			// 车辆牌照号
			plateform.setVehicleNumber(ObjectUtils.toString(val).toUpperCase());
			break;
		case 22:
			// 车辆分类代码
			plateform.setVehicleClassificationCode(ObjectUtils.toString(val));
			break;
		case 23:
			// 车辆载重量(吨)
			plateform.setVehicleTonnage(AppUtils.getBigDecimal(val));
			break;
		case 24:
			// 道路运输证号
			plateform.setRoadTransportCertificateNumber(ObjectUtils.toString(val));
			break;
		case 25:
			// 挂车牌照号
			plateform.setTrailerVehiclePlateNumber(ObjectUtils.toString(val).toUpperCase());
			break;
		case 26:
			// 所有人
			plateform.setOwner(ObjectUtils.toString(val));
			break;
		case 27:
			// 许可证编号
			plateform.setCarPermitNumber(ObjectUtils.toString(val));
			break;
		case 28:
			// 驾驶员姓名
			plateform.setNameOfPerson(ObjectUtils.toString(val));
			break;
		case 29:
			// 驾驶员从业资格证号
			plateform.setQualificationCertificateNumber(ObjectUtils.toString(val));
			break;
		case 30:
			// 驾驶员电话号码
			plateform.setTelephoneNumber(ObjectUtils.toString(val));
			break;
		case 31:
			// 货物名称
			plateform.setDescriptionOfGoods(ObjectUtils.toString(val));
			break;
		case 32:
			// 货物类型分类代码
			plateform.setCargoTypeClassificationCode(ObjectUtils.toString(val));
			break;
		case 33:
			// 货物项毛重 (kg)
			plateform.setGoodsItemGrossWeight(AppUtils.getBigDecimal(val));
			break;
		case 34:
			// 货物体积 (立方米)
			plateform.setCube(AppUtils.getBigDecimal(val));
			break;
		case 35:
			// 货物总件数
			plateform.setTotalNumberOfPackages(AppUtils.getBigDecimal(val).intValue());
			break;
		default:
			break;
		}
	}

}
